package controller;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import model.NguoiDung;

import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import dao.entity.NguoiDungDAO;

public class ChangePassword extends SelectorComposer<Component> {
	private static final long serialVersionUID = 1L;
	@Wire
	private Textbox matkhaucu;
	@Wire
	private Textbox matkhaumoi;
	@Wire
	private Textbox nhaplai;

	@Listen("onClick=#thaydoi")
	public void changePass() {
		String email = (String) Sessions.getCurrent().getAttribute("email");
		NguoiDungDAO dao = new NguoiDungDAO();
		List<NguoiDung> listND = dao.findByCriteria(Restrictions.eq("email",
				email));
		int id = listND.get(0).getId_NguoiDung();
		String matKhauCu = listND.get(0).getPassWord();
		if (!SHA1.getSHA1(matkhaucu.getValue()).equals(matKhauCu)) {
			throw new WrongValueException(matkhaucu, "Sai password");
		} else {
			if (!matkhaumoi.getValue().equals(nhaplai.getValue())) {
				throw new WrongValueException(nhaplai,
						"Password nhập lại không đúng");
			} else {
				NguoiDung user = new NguoiDung();
				user.setId_NguoiDung(id);
				user.setPassWord(SHA1.getSHA1(matkhaumoi.getValue()));
				System.out.println(matkhaumoi.getValue());
				dao.changePass(user);
				Window window = (Window) Executions.createComponents(
						"changepass_sucess.zul", null, null);
				window.doModal();
			}
		}
	}

	public static void main(String[] args) {
		NguoiDung user = new NguoiDung();
		user.setId_NguoiDung(1);
		user.setPassWord("thantienbut");
		NguoiDungDAO dao = new NguoiDungDAO();
		dao.changePass(user);
	}
}
